package cn.com.libertymutual.sp.biz;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;

import cn.com.libertymutual.core.security.jwt.JwtTokenUtil;
import cn.com.libertymutual.core.security.jwt.JwtUserFactory;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.uuid.UUID;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.TbSpUser;

@Component
public class IdentifierMarkBiz {
	private Logger log = LoggerFactory.getLogger(getClass());
	// @Resource
	// private RedisUtils redis;

	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	private String prefix = "Bearer ";

	/**Remarks: 初次生产请求标识码<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年10月11日上午11:01:49<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @return token
	 */
	public String getIdentifier(HttpServletRequest request, Device device) {

		String userCode = "";//
		String userCodeBs = "";//

		// 校验-请求标识码
		String authToken = request.getHeader(Constants.JWT_TOKEN_NAME);
		if (StringUtils.isBlank(authToken)) {
			userCode = UUID.getShortUuid();
		} else {
			authToken = authToken.substring(7, authToken.length());// 去掉前缀
			String strs[] = this.getUserCodeByToken(request);
			userCode = strs[0];
			userCodeBs = strs[1];
		}
		if (StringUtils.isBlank(userCode)) {
			userCode = UUID.getShortUuid();
		}

		UserDetails userDetails = JwtUserFactory.create(userCode, userCodeBs);
		Map<String, Object> claims = Maps.newHashMap();
		claims.put("userCodeBs", userCodeBs);
		String token = jwtTokenUtil.generateToken(userDetails, claims, device);

		String jwtToken = prefix + token;
		return jwtToken;
	}

	/**Remarks: 用户登录时生产请求标识码<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2018年2月2日下午6:22:58<br>
	 * Project：liberty_sale_plat<br>
	 * @param device
	 * @param userCode
	 * @param userCodeBs
	 * @return
	 */
	public String getIdentifierByLogin(Device device, String userCode, String userCodeBs) {
		UserDetails userDetails = JwtUserFactory.create(userCode, userCodeBs);

		Map<String, Object> claims = Maps.newHashMap();
		claims.put("userCodeBs", userCodeBs);
		String token = jwtTokenUtil.generateToken(userDetails, claims, device);
		return prefix + token;
	}

	/**Remarks: 根据token获取userCode<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2018年2月2日下午6:22:49<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @return
	 */
	public String[] getUserCodeByToken(HttpServletRequest request) {
		String userCodes[] = new String[2];

		// 校验-请求标识码

		String authToken = request.getHeader(Constants.JWT_TOKEN_NAME);
		if (StringUtils.isBlank(authToken)) {
			return userCodes;
		}
		synchronized (authToken) {
			if (StringUtils.isNotBlank(authToken) && authToken.length() > 8) {
				authToken = authToken.substring(7, authToken.length());// 去掉
				userCodes[0] = jwtTokenUtil.getUsernameFromToken(authToken);
				userCodes[1] = jwtTokenUtil.getUserCodeFromToken(authToken); // BS
				return userCodes;
			}
		}

		return userCodes;
	}

	/**Remarks: 根据用户信息设置token返回给客户端<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2018年2月2日下午3:54:20<br>
	 * Project：liberty_sale_plat<br>
	 * @param device
	 * @param response
	 * @param sr
	 */
	public void setHeadersToken(Device device, HttpServletResponse response, ServiceResult sr) {
		if (sr.getState() == ServiceResult.STATE_SUCCESS) {
			TbSpUser user = (TbSpUser) sr.getResult();
			// Current.userCode.set(user.getUserCode());
			// Current.userCodeBs.set(user.getUserCodeBs());
			String token = this.getIdentifierByLogin(device, user.getUserCode(), user.getUserCodeBs());
			response.setHeader(Constants.JWT_TOKEN_NAME, token);
		}
	}

	/**Remarks: 校验请求标识码<br>
	 * Version：1.0<br>
	 * Author：AoYi<br>
	 * DateTime：2017年11月10日下午5:36:53<br>
	 * Project：liberty_sale_plat<br>
	 * @param request
	 * @return
	 */
	public ServiceResult verifyIdentCode(HttpServletRequest request) {
		// 默认为未授权的请求
		ServiceResult sr = new ServiceResult("Unauthorized request(403)", ServiceResult.STATE_APP_EXCEPTION);
		String URI = request.getRequestURI();
		if (URI.indexOf("/sale/nol/") >= 0) {
			// 校验-请求标识码
			String authToken = request.getHeader(Constants.JWT_TOKEN_NAME);
			log.info("{}<====={}", authToken, URI.substring(URI.lastIndexOf("/"), URI.length()));

			if (StringUtils.isBlank(authToken) || authToken.length() < 10) {
				sr.setAppFail("Parameter error");
				return sr;
			}
			authToken = authToken.substring(7);// 去掉前缀
			try {
				if (jwtTokenUtil.validateToken(authToken)) {
					sr.setAppFail("请求超时，请刷新");
					return sr;
				}
			} catch (Exception e) {
				sr.setAppFail("非法访问");
				e.printStackTrace();
				return sr;
			}
		}
		sr.setSuccess();
		sr.setResult("请求成功");
		return sr;
	}
}
